1.code
import React, { useState, useEffect } from 'react';
import style from './ImageFade.module.css';
const images = ['自定義圖片1', '自定義圖片2', '自定義圖片3'];
function ImageFade() {
const [currentImageIndex, setCurrentImageIndex] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
//切換到下一張圖
setCurrentImageIndex((prevIndex) =>
prevIndex === images.length - 1 ? 0 : prevIndex + 1
);
}, 3000);//設置切換間隔時間,單位為毫秒
return () => {
clearInterval(interval);//清除定時器
};
}, []);
return (
<div className={style['image-fade-container']}>
{images.map((image, index) => (
<img
key={index}
src={image}
alt={`Image ${index + 1}`}
className={`${style['image']} ${
index === currentImageIndex ? style['active'] : ''
}`}
/>
))}
</div>
);
}
export default ImageFade;
.image-fade-container {
position: relative;
width: 300px;
height: 200px;
overflow: hidden;
}
.image {
max-width: 50%;
height: auto;
position: absolute;
opacity: 0;
transition: opacity 1s ease-in-out;
}
.image.active {
opacity: 1;
}
2.實作